package multi_thread.advanced;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Cheng Jun
 * Description: 基于 VolatileExample 的代码，演示线程被唤醒会重新加载主内存的数据
 * @version 1.0
 * @date 2022/0/10 11:05
 */
public class VolatileExample1 {

    public static void main(String[] args) throws Exception {
        VolatileBoolean1 volatileBoolean1 = new VolatileBoolean1();
        new Thread(() -> volatileBoolean1.get(), "GetThread").start();
        // 确保get方法先执行
        Thread.sleep(1000);
        new Thread(() -> volatileBoolean1.add(), "AddThread").start();
    }

}

class VolatileBoolean1 {
    static ReentrantLock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();
    // 虽然没有 volatile，但是有锁，线程被唤醒后会重新 加载主内存的数据
    private boolean flag = false;
    private List<Integer> dataList = new ArrayList<>();

    public void add() {
        lock.lock();
        try {
            for (int i = 0; i < 1000; i++) {
                dataList.add(i);
                System.out.println("添加元素i" + i + "成功！");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (dataList.size() == 5) {
                    flag = true;
                    System.out.println("发出通知 flag为true了");
                    condition.signal();
                    break;
                }
            }
        } finally {
            lock.unlock();
        }
    }

    public void get() {
        lock.lock();
        try {
            while (true) {
                System.out.println("-----------------");
                if (flag) {
                    System.out.println("收到通知！");
                    break;
                } else {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        } finally {
            lock.unlock();
        }

    }
}
